/**
 * 
 */
package org.hotpotmaterial.codegenn2.service.impl;

import java.util.Date;
import java.util.List;

import org.hotpotmaterial.codegenn2.common.HmCodeGenConstants;
import org.hotpotmaterial.codegenn2.dao.HmteamAccountMapper;
import org.hotpotmaterial.codegenn2.dto.entity.PageDTO;
import org.hotpotmaterial.codegenn2.dto.request.PageRequestDTO;
import org.hotpotmaterial.codegenn2.dto.request.PasswordRequestDTO;
import org.hotpotmaterial.codegenn2.entity.HmteamAccount;
import org.hotpotmaterial.codegenn2.entity.HmteamAccountExample;
import org.hotpotmaterial.codegenn2.exception.CodeCommonException;
import org.hotpotmaterial.codegenn2.service.IHmteamAccountService;
import org.hotpotmaterial.codegenn2.utils.AESUtil;
import org.hotpotmaterial.codegenn2.utils.MD5Util;
import org.hotpotmaterial.codegenn2.utils.RandomUtil;
import org.hotpotmaterial.codegenn2.utils.RequestUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;

import io.micrometer.core.instrument.util.StringUtils;

/**
 * @author cakydeveloper
 *
 */
@Service
public class HmteamAccountServiceImpl implements IHmteamAccountService {

	@Autowired
	private HmteamAccountMapper accountMapper;

	@Override
	public HmteamAccount findAccountByUsername(Integer type, String username) {
		List<Integer> isDeletedStatus = Lists.newArrayList();
		isDeletedStatus.add(HmCodeGenConstants.DATA_IS_VALID);
		isDeletedStatus.add(HmCodeGenConstants.DATA_IS_TEMP_VALID);
		// 查询构建
		HmteamAccountExample example = new HmteamAccountExample();
		example.createCriteria().andLoginTypeEqualTo(type).andUserNameEqualTo(username).andIsDeletedIn(isDeletedStatus);
		List<HmteamAccount> accounts = accountMapper.selectByExample(example);
		if (null != accounts && !accounts.isEmpty()) {
			return accounts.get(0);
		}
		return null;
	}

	@Override
	public HmteamAccount findAccountByTypeAndExternalId(Integer type, String externalId) {
		HmteamAccountExample example = new HmteamAccountExample();
		example.createCriteria().andLoginTypeEqualTo(type).andExternalIdEqualTo(externalId);
		List<HmteamAccount> accounts = accountMapper.selectByExample(example);
		if (null != accounts && !accounts.isEmpty()) {
			return accounts.get(0);
		}
		return null;
	}

	@Override
	@Transactional
	public HmteamAccount insertAccount(HmteamAccount record) {
		// 获取登录信息
		HmteamAccount loginUser = RequestUtil.getAccountInfo();
		// 判断username,email,mobile是否存在
		List<Integer> isDeletedStatus = Lists.newArrayList();
		isDeletedStatus.add(HmCodeGenConstants.DATA_IS_VALID);
		isDeletedStatus.add(HmCodeGenConstants.DATA_IS_TEMP_VALID);
		HmteamAccountExample example = new HmteamAccountExample();
		// TODO SQL性能优化
		example.or().andUserNameEqualTo(record.getUserName()).andIsDeletedIn(isDeletedStatus);
		if (StringUtils.isNotBlank(record.getEmail())) {
			example.or().andEmailEqualTo(record.getEmail()).andIsDeletedIn(isDeletedStatus);
		}
		if (StringUtils.isNotBlank(record.getMobile())) {
			example.or().andMobileEqualTo(record.getMobile()).andIsDeletedIn(isDeletedStatus);
		}
		List<HmteamAccount> accounts = accountMapper.selectByExample(example);
		if (!accounts.isEmpty()) {
			throw new CodeCommonException("用户名/Email/手机号已被注册");
		}
		// 密码AES解密
		String pass = AESUtil.decrypt(record.getPassword(), HmCodeGenConstants.AES_PASSWORD_TRANS_KEY);
		// md5加密
		String md5Pass = MD5Util.encrypt(pass);
		record.setPassword(md5Pass);
		// 记录信息
		record.setCreatedAt(new Date());
		record.setCreatedBy(loginUser.getUserName());
		record.setLastUpdatedAt(record.getCreatedAt());
		record.setLastUpdatedBy(loginUser.getUserName());
		record.setLastUpdatedTraceid(loginUser.getTraceId());
		accountMapper.insertSelective(record);
		return record;
	}

	@Override
	@Transactional
	public HmteamAccount updateAccount(Long id, HmteamAccount record) {
		// 获取登录信息
		HmteamAccount loginUser = RequestUtil.getAccountInfo();
		HmteamAccount currentRecord = accountMapper.selectByPrimaryKey(id);
		if (null != currentRecord) {
			// 不能更新密码和用户名
			record.setPassword(null);
			record.setUserName(null);
			// 更新
			record.setId(id);
			// 记录信息
			record.setLastUpdatedAt(new Date());
			record.setLastUpdatedBy(loginUser.getUserName());
			record.setLastUpdatedTraceid(loginUser.getTraceId());
			accountMapper.updateByPrimaryKeySelective(record);
		}
		return record;
	}

	@Override
	public PageDTO<HmteamAccount> findAccountsByUsername(PageRequestDTO searchDTO) {
		HmteamAccountExample example = new HmteamAccountExample();
		if (null != searchDTO.getSearchParams() && null != searchDTO.getSearchParams().get("userName")) {
			example.createCriteria().andUserNameLike("%" + (String) searchDTO.getSearchParams().get("userName") + "%");
		}
		example.setOrderByClause("id desc");
		// 分页查询
		Page<HmteamAccount> page = PageHelper.startPage(searchDTO.getPageNum(), searchDTO.getPageSize())
				.doSelectPage(() -> accountMapper.selectByExample(example));
		// 构建返回参数
		return PageDTO.<HmteamAccount>builder().pageNum(page.getPageNum()).pageSize(page.getPageSize())
				.total(page.getTotal()).data(page.getResult()).build();
	}

	@Override
	@Transactional
	public void updatePassword(Long id, PasswordRequestDTO password) {
		// 获取登录信息
		HmteamAccount loginUser = RequestUtil.getAccountInfo();
		HmteamAccount currentRecord = accountMapper.selectByPrimaryKey(id);
		if (null != currentRecord) {
			HmteamAccount record = new HmteamAccount();
			// AES解密
			String currentPass = AESUtil.decrypt(password.getCurrentPassword(),
					HmCodeGenConstants.AES_PASSWORD_TRANS_KEY);
			// md5加密
			String md5CurPass = MD5Util.encrypt(currentPass);
			// 判断现有密码是否正确
			if (!md5CurPass.equals(currentRecord.getPassword())) {
				throw new CodeCommonException("原密码不正确");
			}
			// 新密码md5
			String newPass = AESUtil.decrypt(password.getNewPassword(), HmCodeGenConstants.AES_PASSWORD_TRANS_KEY);
			String md5NewPass = MD5Util.encrypt(newPass);
			// 设置型密码
			record.setPassword(md5NewPass);
			// 更新
			record.setId(id);
			// 状态
			record.setIsDeleted(HmCodeGenConstants.DATA_IS_VALID);
			// 记录信息
			record.setLastUpdatedAt(new Date());
			record.setLastUpdatedBy(loginUser.getUserName());
			record.setLastUpdatedTraceid(loginUser.getTraceId());
			accountMapper.updateByPrimaryKeySelective(record);
		}

	}

	@Override
	@Transactional
	public HmteamAccount resetPassword(Long id) {
		// 获取登录信息
		HmteamAccount loginUser = RequestUtil.getAccountInfo();
		HmteamAccount currentRecord = accountMapper.selectByPrimaryKey(id);
		if (null != currentRecord) {
			// 生成随机密码
			String randomPass = RandomUtil.getRandom(16, RandomUtil.TYPE.LETTER_CAPITAL_NUMBER);
			HmteamAccount record = new HmteamAccount();
			// md5加密
			String md5RandomPass = MD5Util.encrypt(randomPass);
			// 设置型密码
			record.setPassword(md5RandomPass);
			// 更新
			record.setId(id);
			// 状态
			record.setIsDeleted(HmCodeGenConstants.DATA_IS_TEMP_VALID);
			// 记录信息
			record.setLastUpdatedAt(new Date());
			record.setLastUpdatedBy(loginUser.getUserName());
			record.setLastUpdatedTraceid(loginUser.getTraceId());
			accountMapper.updateByPrimaryKeySelective(record);
		}
		return null;
	}

	@Override
	@Transactional
	public void logicDeleteAccount(Long id) {
		// 获取登录信息
		HmteamAccount loginUser = RequestUtil.getAccountInfo();
		HmteamAccount currentRecord = accountMapper.selectByPrimaryKey(id);
		if (null != currentRecord) {
			HmteamAccount record = new HmteamAccount();
			record.setIsDeleted(HmCodeGenConstants.DATA_IS_INVALID);
			// 更新
			record.setId(id);
			// 记录信息
			record.setLastUpdatedAt(new Date());
			record.setLastUpdatedBy(loginUser.getUserName());
			record.setLastUpdatedTraceid(loginUser.getTraceId());
			accountMapper.updateByPrimaryKeySelective(record);
		}
	}

}
